<template>
  <n-space vertical>
    <template v-for="attribute in attributes" :key="attribute.id">
      <div class="select-title">
        <span>{{ attribute.name }}</span>
      </div>
      <n-grid x-gap="10" y-gap="10" :col="24">
        <n-gi
          span="6"
          v-for="attributeValue in attribute.values"
          :key="attributeValue.id"
        >
          <div
            class="custom-choose-item custom-choose-item--small flex items-center justify-center"
            :class="{
              'custom-choose-item--active': isSelected(
                attribute.id,
                attributeValue.id
              ),
            }"
            @click.stop="handleSelectAttribute(attribute.id, attributeValue.id)"
          >
            <div class="title">
              <span> {{ attributeValue.name }} </span>
            </div>
          </div>
        </n-gi>
      </n-grid>
    </template>
  </n-space>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { debounce, get } from "lodash-es";
import { getAttributeByProductId } from "@/api/product/productAttribute.api";
import { getTradeinVariant } from "@/api/product/product.api";
import { Attribute } from "@/types/model/product/vos/attributes.vo";
import { IChooseGeneralProps } from "./props";

const emits = defineEmits(["selected"]);

const props = withDefaults(defineProps<IChooseGeneralProps>(), {
  productId: "",
});

const initLoading = ref<boolean>(true);
const attributes = ref<Attribute[]>([]);
const selectedAttribute = ref<Recordable>({});

const handleGetAttributes = async () => {
  initLoading.value = true;
  try {
    const res = await getAttributeByProductId(props.productId);
    const _attributes = get(res, "result") || [];
    let _selectedVaribute: any = {};
    if (_attributes.length) {
      _attributes.forEach((attribute) => {
        _selectedVaribute[attribute.id] = "";
      });
    }
    selectedAttribute.value = _selectedVaribute;
    attributes.value = _attributes;
    console.log(selectedAttribute.value);
  } finally {
    initLoading.value = false;
  }
};

const handleSelectAttribute = debounce(function (
  attributeId: string,
  attributeValueId: string
) {
  if (selectedAttribute.value.hasOwnProperty(attributeId)) {
    selectedAttribute.value[attributeId] = attributeValueId;
  }

  const isFull = checkAttributeSelectedFull();
  if (isFull) {
    // 选中所有属性
    handleGetTradeInVariant();
  }
},
200);

const checkAttributeSelectedFull = () => {
  let flag = true;
  for (const attrId in selectedAttribute.value) {
    if (!selectedAttribute.value[attrId]) {
      flag = false;
      break;
    }
  }
  return flag;
};

const handleGetTradeInVariant = async () => {
  let _attributes = [];
  for (const attrId in selectedAttribute.value) {
    const attrValueId = selectedAttribute.value[attrId];
    if (attrValueId) {
      _attributes.push({
        attrId: attrId,
        attrValueId: attrValueId,
      });
    }
  }
  const params = {
    productId: props.productId,
    attributes: _attributes,
  };

  const res = await getTradeinVariant(params);
  console.log(res);
  const variant = get(res, "result") || {};
  emits("selected", variant);
};

const isSelected = (attributeId: string, attributeValueId: string) => {
  return selectedAttribute.value[attributeId] === attributeValueId;
};

const init = () => {
  handleGetAttributes();
};

onMounted(() => {
  init();
});
</script>
